package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.GenerateCodeParams;
import com.isunland.managesystem.entity.QRCode;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import org.json.JSONException;

/**
 * 二维码
 */
public class GenerateCodeFragment extends BaseFragment {
  @BindView(R.id.iv_QRcode_generateCode) ImageView ivQRcodeGenerateCode;
  private Bitmap mBitmap;//二维码对象
  private GenerateCodeParams mParams;

  @Override public void initData() {
    super.initData();
    mParams = mBaseParams instanceof GenerateCodeParams ? (GenerateCodeParams) mBaseParams
        : new GenerateCodeParams();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_generrate_code, container, false);
    ButterKnife.bind(this, v);
    return v;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    if (mParams.isScan()) scan();
    if (mParams.isGenerate()) generate(mParams.getUrl());
  }

  /** 自动生成二维码 */
  private void generate(String url) {
    try {
      ivQRcodeGenerateCode.setVisibility(View.VISIBLE);
      mBitmap = Create2DCode(url);
      ivQRcodeGenerateCode.setImageBitmap(mBitmap);
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e("generate qrcode error", e);
    }
  }

  /**
   * 用字符串生成二维码
   */
  public Bitmap Create2DCode(String str) throws WriterException {
    //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
    BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 300, 300);
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    //二维矩阵转为一维像素数组,也就是一直横着排了
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        if (matrix.get(x, y)) {
          pixels[y * width + x] = 0xff000000;
        }
      }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    //通过像素数组生成bitmap,具体参考api
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
  }

  @Override public void onDestroy() {
    if (mBitmap != null) {
      mBitmap.recycle();
      mBitmap = null;
    }
    super.onDestroy();
  }

  /**
   * 打开二维码扫描
   */
  private void scan() {
    /**
     * 提高屏幕亮度
     */
    //WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
    //lp.screenBrightness = 1.0f;
    //mActivity.getWindow().setAttributes(lp);
    //IntentIntegrator.forSupportFragment(this).initiateScan();

    IntentIntegrator integrator = IntentIntegrator.forSupportFragment(this);
    //integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
    //integrator.setPrompt("会议签到");
    //integrator.setCameraId(0);  // Use a specific camera of the device
    integrator.setBeepEnabled(false);//声音
    integrator.setOrientationLocked(false);//同时设置manifest.

    integrator.setBarcodeImageEnabled(false);//是否保存二维码
    integrator.initiateScan();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((resultCode == Activity.RESULT_CANCELED) && (requestCode
        == IntentIntegrator.REQUEST_CODE)) {
      //如果在二维码扫描页面点击了返回,结束当前页面.
      mActivity.finish();
      return;
    }
    try {
      IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
      QRCode code = MyUtils.inflate(result.getContents(), QRCode.class);
      //noinspection ConstantConditions
      if (code.getType() == QRCode.TYPE_MEETING_SIGN) volleyPostMeetingSign(code.getId());
    } catch (Exception e) {
      e.printStackTrace();
      MyUtils.showConfirmDialog(mActivity, "无法识别二维码信息", true);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostMeetingSign(String id) {
    if (MyStringUtil.isEmpty(id)) {
      MyUtils.showConfirmDialog(mActivity, "信息为空,无法签到!", true);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_MEETING_SIGN);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainId", id);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.showConfirmDialog(mActivity, getString(R.string.failure_operation), true);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        BaseOriginal result = inflate(json);
        MyUtils.showConfirmDialog(mActivity, result.getMessage(), true);
      }
    });
  }
}
